Ext.onReady(function()
    {
      
        // HANDLER AJAX
        var h_crear_success = function(obj){
            X.reload('listGrid');
            X.set('creaUsername',   '');
            X.set('creaPassword',   '');
            X.set('creaConfirmar',  '');
            X.set('creaNombre',     '');
            X.set('creaApellido',   '');
            X.set('creaEmail',      '');
            X.set('creaCargo',      '');
            X.set('creaDocumento',  '');
            X.set('creaTelefono',   '');
            X.get('CreaSexo').clearValue();

            var grid = X.get('configGrid');
            var store = X.get('storeConfig');
            var rowCount = store.getCount();
            for(var c=0;c<rowCount;c++){
                grid.store.removeAt(0);
            }

            X.focus('creaUsername', '');
        }
        var h_crear_failure = function(obj){
            X.focus('creaUsername');
        }

        // HANDLE CHECK
        var h_empty_nombre = function()  {
            X.focus('creaUsername');
        }
        var h_empty_password     = function(){
            X.focus('creaPassword');
        }
        var h_empty_confirmar    = function(){
            X.focus('creaConfirmar');
        }
        var h_different_password = function(){
            X.focus('creaPassword');
        }
        var h_empty_sex=function(){
            X.focus('CreaSexo')
        }
        var columnRenderer = function(value){
            var combo = this.editor
            var r = combo.findRecord(combo.valueField, value);
            return r ? r.get(combo.displayField) : combo.valueNotFoundText;
        }
        // STORE
        X.aStore({
            id     : 'CreaStoreSexo',
            fields : [ 'idSexo','Sexo' ],
            data   : [
            [1,'Masculino'],[2,'Femenino']
            ]
        });
        X.store({
            id     : 'creaStoreDpto',
            fields : [
            'idDepartamento',
            'nombreD',
            ]            
        });

       
            
        X.store({
            id     : 'creaStorePerfil',
            fields : [
            'idPerfil',
            'nombre',
            ]
        });

        X.store({
            id     : 'storeConfig',
            fields : [ 'perfil','departamento']
        });

        var colModel = new Ext.grid.ColumnModel({
            defaults: {
                menuDisabled: true
            },
            columns: [
            {
                header: 'Perfil',
                dataIndex: 'perfil',
                width : 196,
                editor: new X.form.combo({
                    dfield  :'nombre',
                    vfield  :'idPerfil',
                 
                    storeId :'creaStorePerfil'
                }),
                renderer: columnRenderer
            },{
                header: 'Departamento',
                dataIndex: 'departamento',
                width : 196,
                editor: new X.form.combo({
                    dfield  :'nombreD',
                    vfield  :'idDepartamento',
                
                    storeId :'creaStoreDpto'
                }),
                renderer: columnRenderer
            }]
        });
        X.grid.editor({
            id          : 'configGrid',
            title       : 'Configuracion',
            collapsed   : false,
            height      : 200,
            width       : 400,
            cm          : colModel,
            storeId     : 'storeConfig',
            x           : 10,
            y           : 350,
            tbar : new Ext.Toolbar({
                items:[
                X.form.button({
                    text:'Agregar',
                    id:'addConfig'//, icon:'/img/icon_agregar.png'
                }),'-',
                X.form.button({
                    text:'Eliminar',
                    id:'remConfig'/*, icon:'/img/icon_agregar.png'*/
                })
                ]
            })
        });


        // FORM
        X.form.panel({
            title  : 'Crear Usuario',
            id     : 'creaForm',
            height : 630,
            width  : 500,
            items  : [
            X.form.label ({
                x:10,
                y:16,
                text:'Usuario:'
            }),
            X.form.label ({
                x:10,
                y:46,
                text:'Contraseña:'
            }),
            X.form.label ({
                x:10,
                y:76,
                text:'Confirmar:'
            }),
            X.form.label ({
                x:10,
                y:106,
                text:'Nombre:'
            }),
            X.form.label ({
                x:10,
                y:136,
                text:'Apellido:'
            }),
            X.form.label ({
                x:10,
                y:166,
                text:'Documento:'
            }),
            X.form.label ({
                x:10,
                y:196,
                text:'E-mail:'
            }),
            X.form.label ({
                x:10,
                y:226,
                text:'Telefono:'
            }),
            X.form.label ({
                x:10,
                y:256,
                text:'Cargo:'
            }),
            X.form.label ({
                x:10,
                y:286,
                text:'Sexo:'
            }),
            X.form.combo({
                id:'CreaSexo',
                x:90,
                y:286,
                width:100,
                dfield  :'Sexo',
                vfield  :'idSexo',
                storeId :'CreaStoreSexo'
            }),
            X.form.text  ({
                x:90,
                y:10,
                width:300,
                id:'creaUsername',
                maxlen:64
            }),
            X.form.pass  ({
                x:90,
                y:46,
                width:300,
                id:'creaPassword',
                maxlen:32
            }),
            X.form.pass  ({
                x:90,
                y:76,
                width:300,
                id:'creaConfirmar',
                maxlen:32
            }),
            X.form.text  ({
                x:90,
                y:106,
                width:300,
                id:'creaNombre',
                maxlen:64
            }),
            X.form.text  ({
                x:90,
                y:136,
                width:300,
                id:'creaApellido',
                maxlen:64
            }),
            X.form.number  ({
                x:90,
                y:166,
                width:300,
                id:'creaDocumento',
                maxlen:12
            }),
            X.form.email  ({
                x:90,
                y:196,
                width:300,
                id:'creaEmail',
                maxlen:64
            }),
            X.form.text  ({
                x:90,
                y:226,
                width:300,
                id:'creaTelefono',
                maxlen:64
            }),
            X.form.text  ({
                x:90,
                y:256,
                width:300,
                id:'creaCargo',
                maxlen:64
            }),
            X.form.button({
                x:90,
                y:560,
                width:80,
                id:'creaCrear',
                text:'Crear'
            }),
            X.form.button({
                x:175,
                y:560,
                width:80,
                id:'creaCancelar',
                text:'Cancelar'
            }),X.form.combo({
                id:'CreaSexo',
                x:90,
                y:286,
                width:100,
                dfield  :'Sexo',
                vfield  :'idSexo',
                storeId :'CreaStoreSexo'
            }),
            X.get('configGrid')
            ]
        });


        // EVENTOS
        X.event.jump('creaUsername',   'creaPassword'       );
        X.event.jump('creaPassword',        'creaConfirmar'      );

        X.event.button('addConfig', function(){
            var grid = X.get('configGrid');
            grid.stopEditing();
            grid.store.insert(0, new grid.store.recordType({}));
            grid.startEditing(0,0);
            grid.getSelectionModel().selectRow(0);
        });

        X.event.button('remConfig', function(){
            var grid = X.get('configGrid');
            var record = grid.getSelectionModel().getSelected();
            if (record) {
                var index = grid.store.indexOf(record);
                grid.store.removeAt(index);
                if (index < grid.store.getCount())
                    grid.getSelectionModel().selectRow(index);
                else
                    grid.getSelectionModel().selectRow(index-1);
            }
        });
        
        // EVENT
        X.event.button('creaCrear', function(){
            var store = X.get('storeConfig');
            var rowCount = store.getCount();
            if (X.isempty('creaUsername'))
                X.msg.failure('Complete el campo "Usuario".', h_empty_nombre);
            else if (X.isempty('creaPassword'))
                X.msg.failure('Complete el campo "Contraseña".', h_empty_password);
            else if (X.isempty('creaConfirmar'))
                X.msg.failure('Complete el campo "Confirmar".', h_empty_confirmar);
            else if (X.value('creaPassword')!=X.value('creaConfirmar'))
                X.msg.failure('El campo "Contraseña" debe ser igual al campo "Confirmar".', h_different_password);
            else if (X.isempty('CreaSexo'))
                X.msg.failure('Debe elegir el sexo', h_empty_sex);
            else if(rowCount<=0)
                X.msg.failure('Debe definir al menos una configuracion');
            else{
                var flag=0;
                var grid = X.get('configGrid');
                for (var i=0; i<rowCount; i++){
                    var record = store.getAt(i);
                    
                    if(!(record.get('perfil'))){
                        grid.getSelectionModel().selectRow(i);
                        X.msg.failure('Debe especificar el perfil');
                        flag=1;
                    }
                    if(!(record.get('departamento'))){
                        grid.getSelectionModel().selectRow(i);
                        X.msg.failure('Debe especificar el departamento');
                        flag=1;
                    }
                }

                grid.getSelectionModel().selectAll();
                var sm = grid.getSelectionModel().getSelections();
                var configs = new Array();
                for (i=0; i<=sm.length-1; i++) {
                    var data = {
                        perfil:'',
                        departamento:''
                    };
                   
                    data.perfil=sm[i].get('perfil');
                    data.departamento=sm[i].get('departamento');
                    configs.push(data);
                    delete data;
                    data = {};
                }
                if (flag==0){
                    X.ajax({
                        url:'/usuario/ajax-crear',
                        targetId:'creaForm',
                        params:{
                            nombreUsuario : X.value('creaUsername'),
                            password: X.value('creaPassword'),
                            nombre: X.value('creaNombre'),
                            apellido: X.value('creaApellido'),
                            documento: X.value('creaDocumento'),
                            telefono: X.value('creaTelefono'),
                            cargo: X.value('creaCargo'),
                            email: X.value('creaEmail'),
                            sexo:X.value('CreaSexo'),
                            configuraciones: Ext.encode(configs)
                        },
                        afterSuccess:h_crear_success,
                        afterFailure:h_crear_failure
                    });
                }

            }
        }
        );

        X.event.button('creaCancelar', function(){
            X.hide('creaWindow');
        });


        // WINDOW
        X.win.panel({
            id            : 'creaWindow',
            defaultButton : 'creaUsername',
            resizable: false,
            items         : X.get('creaForm')
        });

        X.get('creaWindow').begin = function(){
            // el if para asegurar abrir una sola ventana (aunque sea modal)
            if (X.get('creaWindow').isVisible()==false){
                X.reload('listGrid');
                X.set('creaUsername',   '');
                X.set('creaPassword',   '');
                X.set('creaConfirmar',  '');
                X.set('creaNombre',     '');
                X.set('creaApellido',   '');
                X.set('creaEmail',      '');
                X.set('creaCargo',      '');
                X.set('creaDocumento',  '');
                X.set('creaTelefono',   '');
                X.get('CreaSexo').clearValue();

                var grid = X.get('configGrid');
                var store = X.get('storeConfig');
                var rowCount = store.getCount();
                for(var c=0;c<rowCount;c++){
                    grid.store.removeAt(0);
                }

                X.focus('creaUsername', '');
                X.show('creaWindow');
            }
        }
    });



